// 1.从vue-router中导入两个方法
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.inc(0.4) // 用于增加加载速度，表示要增加的进度值

// easing：设置进度条动画的缓动函数为 ease
// speed 设置进度条动画的速度为 500 毫秒，越大越慢。
// showSpinner设置是否显示加载进度条旁边的旋转图标
NProgress.configure({ easing: 'ease', speed: 50, showSpinner: true })

// 2.导入业务组件
import Login from '../views/Login.vue'
import Cases from '../views/auto/Cases.vue'
import Requests from '../views/auto/Requests.vue'
import Plans from '../views/auto/Plans.vue'
import Reports from '../views/auto/Reports.vue'

// import Home from '../views/Home.vue'

// 3.创建路由器
const router = createRouter({
  // 3.1 history模式（A.web模式，B.Hash模式）
  history: createWebHistory(import.meta.env.BASE_URL),
  // 3.2 路由数组
  routes: [
    // 3.3 每一个路由对象，包含：path、name、component、redirect、【children、meta】
    {
      path: '/login',
      name: 'login',
      component: Login,
      // redirect: '/about'
    },

    {
      path: '/',
      name: 'home',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/Home.vue'),
      // redirect: { name: 'home' }

      children: [
        {
          path: '/cases',
          name: 'cases',
          component: Cases,
        },
        {
          path: '/requests',
          name: 'requests',
          component: Requests,
        },
        {
          path: '/plans',
          name: 'plans',
          component: Plans,
        },
        {
          path: '/reports',
          name: 'reports',
          component: Reports,
        },
      ],
    },
  ],
})

// 1.前置路由守卫
router.beforeEach((to, from, next) => {
  // 进度条开始
  NProgress.start()
  // 1.如果访问的是登录界面或注册等界面
  if (to.path === '/login' || to.path === '/zhuce') {
    next(true) // 放行  或者next()
  } else {
    // 2.其他页面都是需要登录的
    let userId = localStorage.getItem('userId')
    // 2.1 userId存在，表示已经登录
    if (userId) {
      next(true) // 放行
    } else {
      next('/login') // 跳转到登录界面
    }
  }
})

// 2.后置路由守卫
router.afterEach((to, from, next) => {
  NProgress.done() // 结束进度条
})

export default router
